package com.example.loginprojectbackend.controller;

import com.example.loginprojectbackend.pojo.Result;
import com.example.loginprojectbackend.pojo.User;
import com.example.loginprojectbackend.service.UserService;
import com.example.loginprojectbackend.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Validated
/**
 * 用户登录管理
 *  * 邮件发送管理
 *  * 重置密码
 */
@Slf4j
@RestController
public class LoginController {
    @Autowired
    private UserService userService;

    //用户登录
    @PostMapping("/login")
    public Result login(@RequestBody User user ,@RequestParam(defaultValue = "false") boolean remember) {
        User u = userService.login(user);
        //System.out.println(remember);
        System.out.println("Received request body: " + user.toString());
        System.out.println("Remember me flag from request: " + remember);
        //登录成功，生成令牌，下发令牌
        if (u != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",u.getId());
            claims.put("name",u.getName());
            claims.put("roleId",u.getRoleId());

            String jwt = JwtUtils.generateJwt(claims);  //jwt包含了当前登录的员工信息
            u.setToken(jwt);
            System.out.println(remember);
            //尝试增加记住我功能
            if (remember) {
                // 设置JWT Token的cookie，有效期为七天
                HttpHeaders headers = new HttpHeaders();
                headers.set(HttpHeaders.SET_COOKIE, "token=" + jwt + "; Max-Age=604800; Path=/");  // 604800秒等于七天
                // 可能还需要设置HttpOnly和Secure标志，视具体应用的安全需求而定
            }

            return ResponseEntity.status(HttpStatus.OK).body(Result.success(u)).getBody();
        }

        // 登录失败，返回错误信息
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error("用户名或密码错误")).getBody();
    }
    @PostMapping("/valid-reset-email")
    public Result validateResetEmail(@RequestBody User user,
                                     HttpSession session){
        log.info(user.getEmail());
        log.info("发送邮件id"+session.getId());
        String email = user.getEmail();
        String s=userService.sendValidateEmail(email,session.getId(),true);

        if (s==null)
            return  Result.success(session.getId());
        else
            return  Result.error(s);
    }
    @PostMapping("/start-reset")
    public  Result startReset(@RequestBody User user,
                              HttpSession session ){
        log.info(user.getEmail());
        log.info("验证码"+user.getCode());
        log.info("验证码验证id"+user.getSessionId());
        String email = user.getEmail();
        String s=userService.validateOnly(email,user.getCode(),user.getSessionId());
        log.info(s);
        if(s==null){
            session.setAttribute("reset-password",email);
            return Result.success();
        }else{
            return  Result.error("发生错误，请联系工作人员");
        }
    }
    @PostMapping("/do-reset")
    public Result resetPassword(@RequestBody User user,
                                HttpSession session) {
        log.info("重置密码");
        String email = user.getEmail();
        log.info(user.getEmail());
        String password = user.getPassword();
        userService.resetPassword(password, email);
        session.removeAttribute("reset-password");
        return Result.success("密码重置成功");
    }
    @PostMapping("/reset-information")
    public Result resetInformation(@RequestBody User user,
                                   HttpSession session) {
        log.info("修改资料");
        String jobNumber = user.getJobNumber();
        String password = user.getPassword();
        String email=user.getEmail();
        Integer first=user.getFirst();
        userService.resetInformationByJobNumber(password, jobNumber,email,first);

        session.removeAttribute("reset-information");
        return Result.success("修改资料成功");
    }
}
